package hh;

import cn.hutool.json.JSONUtil;
import hh.util.CommonUtil;

import java.util.Stack;

public class LogStack {

    transient long start = System.currentTimeMillis();
    transient long last = System.currentTimeMillis();
    int step;
    Stack<String> logs = new Stack<>();

    public static void main(String[] args) throws Exception {
        LogStack logStack = new LogStack();

        logStack.begin("1");
        Thread.sleep(10);
        logStack.end("完成");

        logStack.begin("2");
        Thread.sleep(10);
        logStack.end("完成");


        logStack.finish("全部完毕");
        System.out.println(JSONUtil.toJsonPrettyStr(logStack));

    }

    public LogStack begin(String msg, Object... args) {
        last = System.currentTimeMillis();
        logs.add(CommonUtil.format(msg, args));
        step++;
        return this;
    }

    public LogStack end(String msg, Object... args) {
        step++;
        String pop = logs.pop();
        long endTime = System.currentTimeMillis();
        pop += CommonUtil.format(msg, args) + " 耗时：" + (endTime - last) + "ms";
        logs.push(pop);
        return this;
    }

    public LogStack finish(String msg, Object... args) {
        step++;
        String format = CommonUtil.format(msg, args);
        format += " 总耗时" + (System.currentTimeMillis() - start) + "ms";
        logs.push(format);
        return this;
    }


    public String add(String msg, Object... args) {
        step++;
        logs.push(CommonUtil.format(msg, args));
        return logs.peek();
    }

    public String addWithStep(String msg, Object... args) {
        step++;
        msg = CommonUtil.format(msg, step);
        logs.push(CommonUtil.format(msg, args));
        return logs.peek();
    }


    public String peek() {
        return logs.peek();
    }


    public String pop() {
        return logs.pop();
    }


    public Stack<String> getLogs() {
        return logs;
    }
}
